import 'package:flutter/material.dart';
import 'package:get/get.dart';

import 'home_logic.dart';
import '../../data/models/prompt_model.dart';
import '../../data/models/tag_model.dart';
import '../../data/widgets/prompt_card.dart';
import '../../data/widgets/search_bar_widget.dart';
import '../../data/widgets/filter_chips.dart';
import '../../data/widgets/sort_menu.dart';
import '../../core/enums/app_enums.dart';
import '../profile/profile_view.dart';

/// 响应式构建器 - Responsive Builder
/// A widget that provides different layouts based on screen size
/// 根据屏幕尺寸提供不同布局的组件
class ResponsiveBuilder extends StatelessWidget {
  /// 构建器函数 - Builder function
  /// Function that receives context and device type to build appropriate UI
  /// 接收上下文和设备类型以构建适当UI的函数
  final Widget Function(BuildContext context, DeviceType deviceType) builder;

  const ResponsiveBuilder({
    super.key,
    required this.builder,
  });

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        DeviceType deviceType;
        // 根据屏幕宽度确定设备类型 - Determine device type based on screen width
        if (constraints.maxWidth < 600) {
          deviceType = DeviceType.mobile;
        } else if (constraints.maxWidth < 1200) {
          deviceType = DeviceType.tablet;
        } else {
          deviceType = DeviceType.desktop;
        }
        return builder(context, deviceType);
      },
    );
  }
}

/// 主页视图 - Home View
/// 显示 Prompt 列表、搜索筛选、快速操作等功能
/// Main view displaying prompt list, search filters, and quick actions
/// This is the only GetView in the home module, all other components are Widgets
/// 这是home模块中唯一的GetView，其他所有组件都是Widget
class HomeView extends GetView<HomeLogic> {
  const HomeView({super.key});

  @override
  Widget build(BuildContext context) {
    // GetBuilder作为最外层包裹Widget - GetBuilder as the outermost wrapper widget
    // 每个View中只能有一个GetBuilder - Only one GetBuilder per View
    return GetBuilder<HomeLogic>(
      // 不需要init，因为已在InitialBinding中注册 - No need for init, already registered in InitialBinding
      builder: (controller) {
        return Scaffold(
          // 应用栏 - App Bar
          // Dynamic app bar that changes based on selection mode and current tab
          // 根据选择模式和当前标签动态变化的应用栏
          appBar: _buildAppBar(context, controller),

          // 主体内容 - Body Content
          // Main content area for reactive updates
          // 主内容区域进行响应式更新
          body: Column(
            children: [
              // 搜索栏区域 - Search Bar Area (只在Prompt管理页面显示)
              // Conditionally displayed search bar with advanced search option (only on Prompt Management page)
              // 有条件显示的搜索栏，带有高级搜索选项（仅在Prompt管理页面）
              if (controller.state.tabIndex == 0 && controller.state.showSearchBar)
                _buildSearchBarSection(controller),

              // 筛选标签区域 - Filter Tags Area (只在Prompt管理页面显示)
              // Tag chips for filtering prompts by categories (only on Prompt Management page)
              // 用于按分类筛选Prompt的标签芯片（仅在Prompt管理页面）
              if (controller.state.tabIndex == 0)
                _buildFilterChipsSection(controller),

              // 主内容区域 - Main Content Area
              // Expandable content area for prompt list or other pages
              // 用于Prompt列表或其他页面的可扩展内容区域
              Expanded(
                child: _buildMainContent(context, controller),
              ),
            ],
          ),

          // 浮动操作按钮 - Floating Action Button (只在Prompt管理页面显示)
          // Context-sensitive FAB that changes based on selection mode and current tab
          // 根据选择模式和当前标签变化的上下文敏感浮动按钮（仅在Prompt管理页面）
          floatingActionButton: controller.state.tabIndex == 0 
              ? (controller.state.isSelectionMode
                  ? _buildSelectionFAB(controller)
                  : FloatingActionButton(
                      onPressed: controller.createNewPrompt,
                      tooltip: '创建新 Prompt',
                      child: const Icon(Icons.add),
                    ))
              : null,

          // 底部导航栏 - Bottom Navigation Bar
          // Unified bottom navigation for all screen sizes
          // 适用于所有屏幕尺寸的统一底部导航
          bottomNavigationBar: _buildBottomNavigationBar(context, controller),
        );
      },
    );
  }

  /// 构建应用栏 - Build App Bar
  /// Returns appropriate app bar based on current mode and tab
  /// 根据当前模式和标签返回适当的应用栏
  PreferredSizeWidget _buildAppBar(BuildContext context, HomeLogic controller) {
    // 选择模式下显示选择应用栏 (只在Prompt管理页面) - Show selection app bar in selection mode (only on Prompt Management page)
    if (controller.state.isSelectionMode && controller.state.tabIndex == 0) {
      return _buildSelectionAppBar(controller);
    }

    // 根据当前标签显示不同的应用栏 - Show different app bar based on current tab
    switch (controller.state.tabIndex) {
      case 0: // Prompt管理页面 - Prompt Management Page
        return AppBar(
          title: const Text('Prompt Manager'),
          centerTitle: true,
          actions: [
            // 搜索按钮 - Search Button
            // Toggle search bar visibility
            // 切换搜索栏可见性
            IconButton(
              icon: Icon(
                  controller.state.showSearchBar ? Icons.search_off : Icons.search),
              onPressed: controller.toggleSearchBar,
              tooltip: controller.state.showSearchBar ? '关闭搜索' : '搜索',
            ),

            // 视图模式切换 - View Mode Toggle
            // Switch between list and grid view
            // 在列表视图和网格视图之间切换
            IconButton(
              icon: Icon(controller.state.viewMode == ViewMode.list
                  ? Icons.grid_view
                  : Icons.view_list),
              onPressed: () {
                controller.toggleViewMode();
              },
              tooltip: controller.state.viewMode == ViewMode.list ? '网格视图' : '列表视图',
            ),

            // 排序菜单 - Sort Menu
            // Dropdown menu for sorting options
            // 排序选项的下拉菜单
            SortMenu(
              currentSortType: controller.state.sortType,
              onSortChanged: controller.setSortType,
            ),

            // 更多操作菜单 - More Actions Menu
            // Popup menu with additional actions
            // 包含附加操作的弹出菜单
            PopupMenuButton<String>(
              onSelected: (value) => _handleMenuAction(value, controller),
              itemBuilder: (context) => [
                const PopupMenuItem(
                  value: 'select_mode',
                  child: ListTile(
                    leading: Icon(Icons.checklist),
                    title: Text('选择模式'),
                    contentPadding: EdgeInsets.zero,
                  ),
                ),
                const PopupMenuItem(
                  value: 'refresh',
                  child: ListTile(
                    leading: Icon(Icons.refresh),
                    title: Text('刷新'),
                    contentPadding: EdgeInsets.zero,
                  ),
                ),
              ],
            ),
          ],
        );
      case 1: // 社区分享页面 - Community Sharing Page
        return AppBar(
          title: const Text('社区分享'),
          centerTitle: true,
        );
      case 2: // 团队管理页面 - Team Management Page
        return AppBar(
          title: const Text('团队管理'),
          centerTitle: true,
        );
      case 3: // 我的页面 - My Page
        return AppBar(
          title: const Text('我的'),
          centerTitle: true,
        );
      default:
        return AppBar(
          title: const Text('Prompt Manager'),
          centerTitle: true,
        );
    }
  }

  /// 构建搜索栏区域 - Build Search Bar Section
  /// Widget for search functionality with advanced search option
  /// 具有高级搜索选项的搜索功能组件
  Widget _buildSearchBarSection(HomeLogic controller) {
    return Container(
      margin: const EdgeInsets.all(16),
      child: Row(
        children: [
          // 搜索输入框 - Search Input Field
          // Expandable search bar with clear functionality
          // 具有清除功能的可扩展搜索栏
          Expanded(
            child: SearchBarWidget(
              controller: controller.state.searchController,
              onChanged: controller.searchPrompts,
              onSubmitted: controller.searchPrompts,
              hintText: '搜索 Prompt...',
              onClear: () => controller.searchPrompts(''),
            ),
          ),
          const SizedBox(width: 8),

          // 高级搜索按钮 - Advanced Search Button
          // Button to open advanced search dialog
          // 打开高级搜索对话框的按钮
          IconButton(
            onPressed: controller.showAdvancedSearch,
            icon: const Icon(Icons.tune),
            tooltip: '高级搜索',
            style: IconButton.styleFrom(
              backgroundColor: Get.theme.primaryColor.withOpacity(0.1),
              foregroundColor: Get.theme.primaryColor,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建筛选标签区域 - Build Filter Chips Section
  /// Widget for tag-based filtering
  /// 基于标签的筛选组件
  Widget _buildFilterChipsSection(HomeLogic controller) {
    return FilterChips(
      // 获取所有可用标签 - Get all available tags
      // Convert string tags to TagModel objects for the widget
      // 将字符串标签转换为TagModel对象供组件使用
      allTags: controller
          .getAllTags()
          .map((tag) => TagModel(name: tag, id: tag, createdAt: DateTime.now()))
          .toList(),
      selectedTags: controller.state.selectedTags.toSet(),
      onTagToggle: controller.toggleTagFilter,
    );
  }

  /// 构建选择模式应用栏 - Build Selection Mode App Bar
  /// App bar displayed during multi-selection mode
  /// 多选模式下显示的应用栏
  PreferredSizeWidget _buildSelectionAppBar(HomeLogic controller) {
    return AppBar(
      // 关闭按钮 - Close Button
      // Exit selection mode
      // 退出选择模式
      leading: IconButton(
        icon: const Icon(Icons.close),
        onPressed: controller.exitSelectionMode,
      ),

      // 选择计数标题 - Selection Count Title
      // Shows number of selected items
      // 显示选中项目数量
      title: Text('已选择 ${controller.state.selectedPromptIds.length} 项'),

      actions: [
        // 全选/取消全选按钮 - Select All / Deselect All Button
        // Toggle selection of all visible items
        // 切换所有可见项目的选择状态
        IconButton(
          icon: Icon(controller.state.selectedPromptIds.length ==
                  controller.state.filteredPrompts.length
              ? Icons.deselect
              : Icons.select_all),
          onPressed: controller.toggleSelectAll,
          tooltip: controller.state.selectedPromptIds.length ==
                  controller.state.filteredPrompts.length
              ? '取消全选'
              : '全选',
        ),

        // 删除选中项按钮 - Delete Selected Button
        // Only shown when items are selected
        // 仅在有选中项目时显示
        if (controller.state.selectedPromptIds.isNotEmpty)
          IconButton(
            icon: const Icon(Icons.delete),
            onPressed: () => _showDeleteConfirmDialog(controller),
            tooltip: '删除选中项',
          ),
      ],
    );
  }

  /// 构建选择模式浮动按钮 - Build Selection Mode FAB
  /// Extended FAB for exiting selection mode
  /// 用于退出选择模式的扩展浮动按钮
  Widget _buildSelectionFAB(HomeLogic controller) {
    return FloatingActionButton.extended(
      onPressed: controller.exitSelectionMode,
      label: const Text('取消选择'),
      icon: const Icon(Icons.close),
    );
  }

  /// 构建主内容区域 - Build Main Content Area
  /// Main content area that displays different pages based on current selection
  /// 根据当前选择显示不同页面的主内容区域
  Widget _buildMainContent(BuildContext context, HomeLogic controller) {
    // 根据当前页面显示内容 - Display content based on current page
    return _buildCurrentPage(controller);
  }

  /// 构建当前页面 - Build Current Page
  /// Renders the appropriate page based on current page state
  /// 根据当前页面状态渲染适当的页面
  Widget _buildCurrentPage(HomeLogic controller) {
    switch (controller.state.tabIndex) {
      case 0:
        return _buildPromptManagementPage(controller);
      case 1:
        return _buildCommunityPage();
      case 2:
        return _buildTeamPage();
      case 3:
        return _buildProfilePage();
      default:
        return _buildPromptManagementPage(controller);
    }
  }

  /// 构建Prompt管理页面 - Build Prompt Management Page
  /// Main page displaying the list of prompts
  /// 显示Prompt列表的主页面
  Widget _buildPromptManagementPage(HomeLogic controller) {
    // 加载状态显示 - Loading State Display
    // Show loading indicator while data is being fetched
    // 在获取数据时显示加载指示器
    if (controller.state.isLoading) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    // 空状态显示 - Empty State Display
    // Show message when no prompts are available
    // 当没有可用Prompt时显示消息
    if (controller.state.filteredPrompts.isEmpty) {
      return _buildEmptyState(controller);
    }

    // 响应式布局 - Responsive Layout
    // Different layouts for different screen sizes
    // 不同屏幕尺寸的不同布局
    return ResponsiveBuilder(
      builder: (context, deviceType) {
        return _buildPromptList(context, controller, deviceType);
      },
    );
  }

  /// 构建Prompt列表 - Build Prompt List
  /// Displays prompts in list or grid format based on view mode
  /// 根据视图模式以列表或网格格式显示Prompt
  Widget _buildPromptList(
      BuildContext context, HomeLogic controller, DeviceType deviceType) {
    // 根据视图模式选择布局 - Choose layout based on view mode
    if (controller.state.viewMode == ViewMode.grid) {
      return _buildGridView(controller, deviceType);
    } else {
      return _buildListView(controller);
    }
  }

  /// 构建网格视图 - Build Grid View
  /// Grid layout for prompt cards
  /// Prompt卡片的网格布局
  Widget _buildGridView(HomeLogic controller, DeviceType deviceType) {
    // 根据设备类型确定列数 - Determine column count based on device type
    int crossAxisCount;
    switch (deviceType) {
      case DeviceType.mobile:
        crossAxisCount = 1;
        break;
      case DeviceType.tablet:
        crossAxisCount = 2;
        break;
      case DeviceType.desktop:
        crossAxisCount = 3;
        break;
    }

    return GridView.builder(
      padding: const EdgeInsets.all(16),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: crossAxisCount,
        crossAxisSpacing: 16,
        mainAxisSpacing: 16,
        childAspectRatio: 1.2,
      ),
      itemCount: controller.state.filteredPrompts.length,
      itemBuilder: (context, index) {
        final prompt = controller.state.filteredPrompts[index];
        return _buildPromptCard(prompt, controller);
      },
    );
  }

  /// 构建列表视图 - Build List View
  /// List layout for prompt items
  /// Prompt项目的列表布局
  Widget _buildListView(HomeLogic controller) {
    return ListView.builder(
      padding: const EdgeInsets.all(16),
      itemCount: controller.state.filteredPrompts.length,
      itemBuilder: (context, index) {
        final prompt = controller.state.filteredPrompts[index];
        return Padding(
          padding: const EdgeInsets.only(bottom: 8),
          child: _buildPromptCard(prompt, controller),
        );
      },
    );
  }

  /// 构建Prompt卡片 - Build Prompt Card
  /// Individual prompt card widget
  /// 单个Prompt卡片组件
  Widget _buildPromptCard(PromptModel prompt, HomeLogic controller) {
    return PromptCard(
      prompt: prompt,
      isSelected: controller.state.selectedPromptIds.contains(prompt.id),
      isSelectionMode: controller.state.isSelectionMode,
      onTap: () => _handlePromptTap(prompt, controller),
      onLongPress: () => _handlePromptLongPress(prompt, controller),
      onFavoriteToggle: () => controller.togglePromptFavorite(prompt.id),
      onEdit: () => controller.editPrompt(prompt.id),
      onDelete: () => _showDeleteSingleConfirmDialog(prompt.id, controller),
      onDuplicate: () => controller.duplicatePrompt(prompt.id),
    );
  }

  /// 构建空状态 - Build Empty State
  /// Widget displayed when no prompts are available
  /// 当没有可用Prompt时显示的组件
  Widget _buildEmptyState(HomeLogic controller) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.description_outlined,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            controller.state.searchKeyword.isNotEmpty
                ? '未找到匹配的 Prompt'
                : '还没有 Prompt',
            style: Theme.of(Get.context!).textTheme.headlineSmall?.copyWith(
                  color: Colors.grey[600],
                ),
          ),
          const SizedBox(height: 8),
          Text(
            controller.state.searchKeyword.isNotEmpty
                ? '尝试调整搜索条件'
                : '点击右下角的 + 按钮创建第一个 Prompt',
            style: Theme.of(Get.context!).textTheme.bodyMedium?.copyWith(
                  color: Colors.grey[500],
                ),
          ),
          if (controller.state.searchKeyword.isEmpty) ...[
            const SizedBox(height: 24),
            ElevatedButton.icon(
              onPressed: controller.createNewPrompt,
              icon: const Icon(Icons.add),
              label: const Text('创建 Prompt'),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建社区页面 - Build Community Page
  /// Placeholder for community sharing functionality
  /// 社区分享功能的占位符
  Widget _buildCommunityPage() {
    return _buildUnderConstruction('社区分享');
  }

  /// 构建公司页面 - Build Company Page
  /// Placeholder for company management functionality
  /// 公司管理功能的占位符
  Widget _buildCompanyPage() {
    return _buildUnderConstruction('公司管理');
  }

  /// 构建团队页面 - Build Team Page
  /// Placeholder for team management functionality
  /// 团队管理功能的占位符
  Widget _buildTeamPage() {
    return _buildUnderConstruction('团队管理');
  }

  /// 构建我的页面 - Build Profile Page
  /// Profile page with settings and user information
  /// 包含设置和用户信息的我的页面
  Widget _buildProfilePage() {
    return const ProfileView();
  }

  /// 构建建设中页面 - Build Under Construction Page
  /// Generic placeholder for unimplemented features
  /// 未实现功能的通用占位符
  Widget _buildUnderConstruction([String? title]) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(
            Icons.construction,
            size: 64,
            color: Colors.grey[400],
          ),
          const SizedBox(height: 16),
          Text(
            title != null ? '$title 功能' : '功能',
            style: Theme.of(Get.context!).textTheme.headlineSmall?.copyWith(
                  color: Colors.grey[600],
                ),
          ),
          const SizedBox(height: 8),
          Text(
            '此功能暂未开放',
            style: Theme.of(Get.context!).textTheme.bodyMedium?.copyWith(
                  color: Colors.grey[500],
                ),
          ),
        ],
      ),
    );
  }

  /// 构建底部导航栏 - Build Bottom Navigation Bar
  /// Navigation bar for switching between different sections
  /// 用于在不同部分之间切换的导航栏
  Widget _buildBottomNavigationBar(BuildContext context, HomeLogic controller) {
    return BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      currentIndex: controller.state.tabIndex,
      onTap: controller.setTabIndex,
      items: const [
        BottomNavigationBarItem(
          icon: Icon(Icons.description),
          label: 'Prompt管理',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.share),
          label: '社区分享',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.group),
          label: '团队管理',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.person),
          label: '我的',
        ),
      ],
    );
  }

  /// 处理菜单操作 - Handle Menu Actions
  /// Processes actions from the popup menu
  /// 处理弹出菜单的操作
  void _handleMenuAction(String action, HomeLogic controller) {
    switch (action) {
      case 'select_mode':
        controller.enterSelectionMode();
        break;
      case 'refresh':
        controller.refreshData();
        break;
    }
  }

  /// 处理Prompt点击 - Handle Prompt Tap
  /// Handles tap events on prompt cards
  /// 处理Prompt卡片的点击事件
  void _handlePromptTap(PromptModel prompt, HomeLogic controller) {
    if (controller.state.isSelectionMode) {
      // 选择模式下切换选择状态 - Toggle selection in selection mode
      controller.togglePromptSelection(prompt.id);
    } else {
      // 普通模式下查看详情 - View details in normal mode
      controller.viewPromptDetail(prompt.id);
    }
  }

  /// 处理Prompt长按 - Handle Prompt Long Press
  /// Handles long press events on prompt cards
  /// 处理Prompt卡片的长按事件
  void _handlePromptLongPress(PromptModel prompt, HomeLogic controller) {
    if (!controller.state.isSelectionMode) {
      // 进入选择模式 - Enter selection mode
      controller.enterSelectionMode();
    }
    // 切换选择状态 - Toggle selection
    controller.togglePromptSelection(prompt.id);
  }

  /// 显示删除确认对话框 - Show Delete Confirmation Dialog
  /// Confirmation dialog for batch deletion
  /// 批量删除的确认对话框
  void _showDeleteConfirmDialog(HomeLogic controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('确认删除'),
        content: Text(
            '确定要删除选中的 ${controller.state.selectedPromptIds.length} 个 Prompt 吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.deleteSelectedPrompts();
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 显示单个删除确认对话框 - Show Single Delete Confirmation Dialog
  /// Confirmation dialog for single prompt deletion
  /// 单个Prompt删除的确认对话框
  void _showDeleteSingleConfirmDialog(String promptId, HomeLogic controller) {
    Get.dialog(
      AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个 Prompt 吗？'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () {
              Get.back();
              controller.deletePrompt(promptId);
            },
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }
}
